import 'package:cloudapp/common/common.dart';
import 'package:cloudapp/esdk/db.dart';
import 'package:cloudapp/items/local_album_item.dart';
import 'package:cloudapp/model/global_info.dart';
import 'package:cloudapp/pages/base.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';

// 本地相册列表
class LocalPicturePage extends StatefulWidget {
  static const pageName = "/local/picture";

  @override
  State<StatefulWidget> createState() {
    return _LocalPicturePage();
  }
}

class _LocalPicturePage extends BaseState<LocalPicturePage> {
  var _list = List<LocalAlbumInfo>();

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, loadAllLocalAlbum);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('本地相册'),
      ),
      body: ListView.builder(
        itemCount: _list.length,
        itemBuilder: (context, index) {
          return LocalAlbumItemWidget(
            info: _list[index],
          );
        },
      ),
    );
  }

  void loadAllLocalAlbum() async {
    var sessionId = GlobalInfo.i().sessionId;
    var result = await PhotoManager.requestPermission();
    if(!result) {
      showToast('权限获取失败');
      return;
    }

    var albumLists = await PhotoManager.getAssetPathList(
      hasAll: false,
    );

    /// 加载相册以及其数据库同步状态
    final nList = List<LocalAlbumInfo>();
    for(var item in albumLists) {
      final album = LocalAlbumInfo(
        id: item.id,
        name: item.name,
        assetCount: item.assetCount,
      );

      // 获取第一张图片的缩略图
      var picFiles = await item.getAssetListRange(start: 1, end: 2);
      if(picFiles.length > 0) {
        album.thumb = await picFiles[0].thumbDataWithSize(128, 128);
      }

      var albumId = album.getIdentify();
      var rs = await DbStorage.i().findLocalAlbum(sessionId, albumId);
      if(rs.length > 0) {
        album.beSync = true;
      }
      nList.add(album);
    }

    setState(() {
      _list.clear();
      for(var item in nList) {
        _list.add(item);
      }
    });
  }
}
